import axios from 'axios'
import rsa from '@/assets/scripts/rsa'

const ROOT = `${window.location.origin}${window.location.pathname}`.replace(/\/$/, '')

function formatUrl(url) {
  return (ROOT + url)
}

function ensureParams(params) {
  if (!params) {
    return {}
  }
  if (params.options) {
    params.options = rsa.encrypt(params.options)
  }
  return params
}

function handleResponse(response, resolve) {
  const { message, data, success } = response.data
  if (!success) {
    throw new Error(message)
  }
  resolve(data)
}

const ajax = {
  get(url, params) {
    return new Promise((resolve, reject) => {
      params = ensureParams(params)
      axios.get(formatUrl(url), params).then(res => {
        handleResponse(res, resolve)
      }).catch(e => {
        reject(e)
      })
    })
  },
  post(url, params) {
    return new Promise((resolve, reject) => {
      params = ensureParams(params)
      axios.post(formatUrl(url), params).then(res => {
        handleResponse(res, resolve)
      }).catch(e => {
        reject(e)
      })
    })
  },
  put(url, params) {
    return new Promise((resolve, reject) => {
      params = ensureParams(params)
      axios.put(formatUrl(url), params).then(res => {
        handleResponse(res, resolve)
      }).catch(e => {
        reject(e)
      })
    })
  },
  delete(url, params) {
    return new Promise((resolve, reject) => {
      params = ensureParams(params)
      axios.delete(formatUrl(url), { params }).then(res => {
        handleResponse(res, resolve)
      }).catch(e => {
        reject(e)
      })
    })
  }
}

export default ajax
